package com.amanda.reggie.service.impl;

import com.amanda.reggie.common.R;
import com.amanda.reggie.entity.User;
import com.amanda.reggie.mapper.UserMapper;
import com.amanda.reggie.service.UserService;
import com.amanda.reggie.utils.SMSUtils;
import com.amanda.reggie.utils.ValidateCodeUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpSession;
import java.util.Map;

/**
 * @author amanda
 * @Description 用户业务实现
 */
@Slf4j
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Autowired
    private UserService userService;

    /**
     * 发送短信验证码
     */
    @Override
    public R<String> sendMsg(User user, HttpSession httpSession) {
        // 1、获取手机号
        String phone = user.getPhone();
        if (StringUtils.isNotEmpty(phone)) {
            // 随机6位验证码
            String code = ValidateCodeUtils.generateValidateCode(6).toString();
            if (phone.equals("手机号")) {
                // 调用腾讯云服务发送短信
                SMSUtils.sendMessage(phone, code);
                // 将验证码存入session
                httpSession.setAttribute(phone, code);
                return R.success("发送短信成功！");
            }else {
                // 模拟业务，穷
                log.info("大众用户登录验证码："+code+"，请在1分钟之内使用！");
                // 将验证码存入session
                httpSession.setAttribute(phone, code);
                return R.success("发送短信成功！");
            }
        }
        return R.error("短信发送失败！");
    }

    @Override
    public R<User> login(Map userMap, HttpSession httpSession) {
        // 1、手机号
        String phone = userMap.get("phone").toString();
        // 2、验证码
        String code = userMap.get("code").toString();
        // 3、Session中存储的验证码
        Object codeInSession = httpSession.getAttribute(phone);
        // 4、比对验证码
        if (null != codeInSession && codeInSession.equals(code)) {
            // 5、判断当前用户是否新用户
            LambdaQueryWrapper<User> userQueryWrapper = new LambdaQueryWrapper<>();
            userQueryWrapper.eq(User::getPhone, phone);
            User user = userService.getOne(userQueryWrapper);
            if (user == null) {
                // 6、自动注册
                user = new User();
                user.setPhone(phone);
                userService.save(user);
            }
            httpSession.setAttribute("user", user.getId());
            return R.success(user);
        }
        return R.error("验证码错误，登录失败！");
    }
}
